package demon3;

import java.util.Arrays;

public class Heap {
    public int useSize;
    public int[] elem;
    public Heap(){
        this.elem=new int[10];
    }
    public void assignment(int[] arr){
        for (int i = 0; i < elem.length; i++) {
            elem[i]=arr[i];
            useSize++;
        }
    }
    public void createHeap(){

        for(int parent=(useSize-1-1)/2;parent>=0;parent--){
            shifDown(parent,useSize);
        }
    }
    public void shifDown(int parent,int end){
        int child=2*parent+1;
        while(child<end){
            if(child+1<end&&elem[child]<elem[child+1]){
                child++;
            }
            if(elem[child]>parent){
                int temp=elem[parent];
                elem[parent]=elem[child];
                elem[child]=temp;
                parent=child;
                child=2*parent+1;
            }else{
                break;
            }
        }
    }
    public boolean isFull(){
        return elem.length==useSize;
    }
    public void offer(int x,int[] array){
        if(isFull()){
            elem=Arrays.copyOf(elem,2*elem.length);
        }
        elem[useSize]=x;
        useSize++;
        sifUp(useSize-1);
    }
    private void sifUp(int child){
        int parent =(child-1)/2;
        while(parent>=0){
            if(elem[child]>elem[parent]){
                int temp=elem[parent];
                elem[parent]=elem[child];
                elem[child]=temp;
                child=parent;
                parent=(child-1)/2;
            }else{
                break;
            }
        }
    }
    public boolean isEmpty(){
        return useSize==0;
    }
    public void swap(int[]elem,int i,int j){
        int temp=elem[i];
        elem[i]=elem[j];
        elem[j]=temp;

    }
    public int poll(){
        if(isFull()){
            return -1;
        }
        swap(elem,0,useSize-1);
        int del=elem[0];
        useSize--;
        shifDown(0,useSize);
        return del;
    }
}
